package yun;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class App {

    private static Long num;

    public static void main( String[] args ) {
        // 文件夹路径
        String path = "D:\\WeChat\\WeChat Files\\wxid_52skih845sb922\\FileStorage\\File\\2022-10\\json";
        num = 0L;
        List<String> jsonList = new ArrayList<>();
        try (Stream<Path> paths = Files.walk(Paths.get(path))){
            List<Path> fileNames = paths
                    .filter(Files::isRegularFile)
                    .collect(Collectors.toList());
            for (Path fileName : fileNames) {
                File file = fileName.toFile();
                if(file.isFile() && file.exists()) {
                    InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
                    BufferedReader br = new BufferedReader(isr);
                    StringBuffer sb = new StringBuffer();
                    String lineTxt = null;
                    while ((lineTxt = br.readLine()) != null) {
                        sb.append(lineTxt);
                    }
                    br.close();
                    jsonList.add(sb.toString());
                } else {
                    System.out.println("文件不存在:" + fileName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 解析JSON
        if (CollectionUtils.isNotEmpty(jsonList)) {
            System.out.println("jsonList: " + jsonList);
            for (String jsonStr : jsonList) {
                Map mapTypes = JSON.parseObject(jsonStr);
                Object dataList = mapTypes.get("dataList");
                // 解析listJSON
                parsingJson(dataList.toString());
            }
        }
        System.out.println("num: " + num);
    }

    static void parsingJson(String jsonStr) {
        if (jsonStr == null) {
            return;
        }
        JSONArray jsonArray = JSON.parseArray(jsonStr);
        if (jsonArray == null || jsonArray.size() == 0) {
            return;
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsObj = jsonArray.getJSONObject(i);
            String shapeType = jsObj.getString("shapeType");
            if ("rectangle".equals(shapeType)) {
                num += 1;
            }
        }
    }
}
